<template>
    <view>
        <!-- 头部固定高度 -->
        <view class="box_1" :style="'height: ' + height + 'px;margin-bottom:28rpx ;'">
            <view class="box_0 flex flex-justify-center flex-align-center" :style="'margin-top: ' + (navTop + 10) + 'px;'" @tap.stop.prevent="btnCode">
                <image src="https://static.lixingpt.com/6854f93c-5a0f-4817-9e33-a1b246be79ec.png" mode="" />
            </view>
        </view>
        <view v-if="!token || !userInfo" class="box_2 flex flex-align-center" style="background-image: url(https://bc-1306761403.cos.ap-shanghai.myqcloud.com/miniapp/vip/bg1.png)">
            <image class="box_3" src="@/static/images/41.png" mode="" />
            <view class="box_4">
                <view class="box_5">Hello！</view>
                <view class="box_6">登录领取会员卡享更多权益</view>
            </view>
            <view class="box_7" @tap="handelLogin">注册/登录</view>
            <view class="box_44 flex flex-justify-center flex-align-center">
                <image src="https://static.lixingpt.com/3f4cf161-d0fc-4628-8291-395545a3e05f.png" mode="" />
            </view>
        </view>
        <view class="box_25" v-else style="background-image: url(https://bc-1306761403.cos.ap-shanghai.myqcloud.com/miniapp/vip/bg1.png)">
            <view class="box_31 flex">
                <image class="box_30" :src="userInfo.head_imgurl" mode="" />
                <view>
                    <view class="box_32">{{ userInfo.nickname }}</view>
                    <view class="box_33 flex flex-align-center">
                        <view class="box_34">
                            <image src="@/static/images/icon_zsh.png" mode="" />
                        </view>
                        <view class="box_35">
                            等级:
                            <text>LV{{ userInfo.level }}</text>
                        </view>
                    </view>
                </view>
                <image v-if="userInfo.level == 1" class="box_42" src="https://bc-1306761403.cos.ap-shanghai.myqcloud.com/715d9925-0320-4ea9-ad7b-0f40b5fb0acf.png" mode="" />
                <image v-if="userInfo.level == 2" class="box_42" src="https://bc-1306761403.cos.ap-shanghai.myqcloud.com/53244581-d3d2-4e7b-b17e-02b11abe8565.png" mode="" />
                <image v-if="userInfo.level == 3" class="box_42" src="https://bc-1306761403.cos.ap-shanghai.myqcloud.com/c7c470f0-0e34-46bd-bfe7-b9af60549e2a.png" mode="" />
                <view class="box_43 flex flex-justify-center flex-align-center" :data-code="userInfo.to_Account" @tap="jumpMember">
                    <image src="@/static/images/icon_qr2.png" mode="" />
                </view>
            </view>
            <view class="box_36">
                积分：
                <text>{{ userInfo.allIntegral }}</text>
            </view>

            <view class="box_37 flex">
                <view>
                    <text class="box_38">{{ userInfo.growth_value }}</text>
                    <text class="box_39">/{{ userInfo.current_level_max_growth_value + userInfo.growth_value }}</text>
                    <text class="box_40">距离下一等级还需要{{ userInfo.current_level_max_growth_value }}经验值</text>
                    <van-progress track-color="#1F51A8" color="#FDFFFF" custom-class="progress" :show-pivot="false" percentage="50" />
                </view>
                <view class="box_41">购物享97折起</view>
            </view>
        </view>

        <view class="box_8">
            <view class="box_9" v-if="!token || !userInfo"></view>
            <view class="box_26" v-if="token && userInfo">
                <view class="box_27" v-if="token && userInfo">
                    <canvas :style="'display: ' + (!overLayshow ? 'block' : 'none')" class="bar_code" canvas-id="bar_code" />
                </view>
                <view class="box_28 flex flex-justify-center">
                    <image v-if="showmember" src="@/pagesOne/static/images/12.png" mode="" @tap.stop.prevent="handelShow" />
                    <image v-else src="@/pagesOne/static/images/11.png" mode="" @tap.stop.prevent="handelShow" />
                    <view class="box_29">{{ wxs.hide(userInfo.to_Account, 3, 7, showmember) }}</view>
                </view>
            </view>
            <view class="box_10 flex flex-justify-around">
                <view class="box_11" :data-item="item" @tap.stop.prevent="jumpPage" v-for="(item, index) in menuList" :key="item.id">
                    <image :src="item.url" mode="" />

                    <view class="box_12">{{ item.name }}</view>
                </view>
            </view>

            <view class="box_13">司机驿站</view>

            <view class="box_14" v-for="(item, index) in storeList" :key="item.id">
                <view class="box_15 flex">
                    <view class="box_16">{{ item.name }}</view>
                    <view class="box_17">营业中</view>
                </view>

                <view class="box_18">营业时间：{{ item.startWorkTime }}～{{ item.endWorkTime }}</view>

                <view class="box_19">{{ item.address }}</view>

                <view class="box_20 flex flex-align-center flex-justify-around">
                    <image src="https://bc-1306761403.cos.ap-shanghai.myqcloud.com/a8114efe-76a4-4988-9891-bff00a11de66.png " mode="" />
                    <view class="box_21" :data-phone="item.phone" @tap.stop.prevent="contact">联系店铺</view>
                </view>

                <view class="box_22" v-if="item.dist"></view>

                <view class="box_23" v-if="item.dist" @tap.stop.prevent="goOrder" :data-item="item" :data-index="index" :data-id="item.id">
                    <image src="@/static/images/24.png" mode="" />
                    <view class="box_24">{{ item.dist }}km</view>
                </view>

                <view
                    v-if="index == 0 && item.dist"
                    class="box_55"
                    style="background-image: url(https://bc-1306761403.cos.ap-shanghai.myqcloud.com/9bf5259b-65fb-4c08-95f9-d60a25ec0680.png); background-size: cover"
                ></view>
            </view>
        </view>

        <view class="Floating_window flex flex-align-center" v-if="token && userInfo && userInfo.capsuleUseRecords && userInfo.capsuleUseRecords.length != 0">
            <image style="width: 36rpx; height: 38rpx; margin-left: 28rpx" src="https://static.lixingpt.com/32cc63a5-342b-4b18-9834-993e587c83a6.png" mode="" />
            <view
                class="Floating_window_text flex flex-column"
                @tap.stop.prevent="jump"
                :data-deviceType="userInfo.capsuleUseRecords[0].deviceType"
                :data-id="userInfo.capsuleUseRecords[0].orderId"
            >
                <view>{{ userInfo.capsuleUseRecords.length }}个设备正在使用中</view>
                <view v-if="userInfo.capsuleUseRecords.length == 1" style="font-size: 20rpx; color: rgba(255, 255, 255, 0.5); font-weight: normal">已使用：{{ byTime }}</view>
            </view>
            <view class="flex Floating_window_view flex-align-center" v-if="userInfo.capsuleUseRecords.length == 1 && userInfo.capsuleUseRecords[0].deviceType === 0">
                <image style="width: 18rpx; height: 20rpx; margin-left: 16rpx" src="  https://static.lixingpt.com/56929f61-7750-4868-a936-22c531f6b58d.png" mode="" />
                <view class="Floating_window_view_text" :data-deviceId="userInfo.capsuleUseRecords[0].deviceId" @tap.stop.prevent="Unlock">解锁</view>
            </view>
        </view>
		
		<!-- 智能Tabbar -->
		<smart-tabbar></smart-tabbar>
    </view>
</template>
<script module="wxs" lang="wxs">
module.exports.hide = function (str, start, end, show) {

  if (show) {
    var s = ''
    for (var i = 0; i < (end - start); i++) {
      s += '*'
    }
    return str.replace(str.substring(start, end), s)
  } else {
    return str
  }

}
</script>
<script>
import SmartTabbar from '@/components/smart-tabbar/index.vue'
import { getRecords, miniAppConfig, getScan, anonymousScan, getInfo, getCoupon } from '@/api/index/index.js';
import { extractUrlParameters, isDuringDate, timeOut, updateTimer } from '@/utils/util';
import { openDoorForApp, openGate, openNormalDoor, openDoorByShopId, takeEnvelopeApi } from '@/api/massageCabin';
import { setUserPermissionLevel } from '@/utils/tabbarPermission.js';
import wxbarcode from 'wxbarcode';
const defalutForm = {
    latitude: '',
    longitude: '',
    rows: 100000
};
export default {
	components: {
		SmartTabbar
	},
    data() {
        return {
            height: getApp().globalData.height,
            navTop: getApp().globalData.navTop,
            menuList: [],
            storeList: [],
            defalutQuery: Object.assign({}, defalutForm),
            token: null, // 新增：登录token
            userInfo: null,
            showmember: true,
            byTime: '00:00:00',
            timer: null,
            str: '',
            show: false,
            overLayshow: false,
            deviceType: '',
            orderId: '',
            deviceId: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        this.getMenu();
        this.getRecords();
        this.getPostioning();
        // wxbarcode.barcode('bar_code', this.data.userInfo.to_Account, 520, 112)
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 获取token
        this.token = uni.getStorageSync('token') || null;
        
        // 如果有token，获取用户信息
        if (this.token) {
            let scanCodeContent = uni.getStorageSync('scanCodeCotent');
            console.log('index:' + scanCodeContent);
            if (scanCodeContent) {
                this.codehandler(scanCodeContent);
                uni.removeStorageSync('scanCodeCotent');
            }
            
            // 调用接口获取最新的用户信息
            getInfo().then((res) => {
                // 根据 rentVIP 字段设置权限
                const permissionLevel = res.data.rentVIP ? 1 : 0;
                console.log('根据 rentVIP 设置权限:', permissionLevel, 'rentVIP:', res.data.rentVIP);
                
                // 设置权限
                setUserPermissionLevel(permissionLevel);
                
                // 如果权限是1，跳转到新首页
                if (permissionLevel === 1) {
                    console.log('权限为1，跳转到新首页');
                    uni.reLaunch({
                        url: '/pages/index/index'
                    });
                    return;
                }
                
                // 权限为0，继续在当前页面
                console.log('权限为0，保持在当前页面');
                if (res.data.capsuleUseRecords && res.data.capsuleUseRecords.length >= 1) {
                    setInterval(() => {
                        this.setData({
                            byTime: updateTimer(new Date(res.data.capsuleUseRecords[0].startTime).getTime(), new Date(res.data.capsuleUseRecords[0].endTime).getTime())
                        });
                    }, 1000);
                }
                
                // 更新用户信息
                this.userInfo = res.data;
                uni.setStorageSync('userInfo', res.data);
                
                // 生成条形码
                if (res.data.to_Account) {
                    wxbarcode.barcode('bar_code', res.data.to_Account, 520, 112);
                }
            }).catch(err => {
                console.error('获取用户信息失败:', err);
                // 如果接口调用失败，清除token和用户信息
                this.token = null;
                this.userInfo = null;
                uni.removeStorageSync('token');
                uni.removeStorageSync('userInfo');
            });
        } else {
            // 没有token，清除用户信息
            this.userInfo = null;
            uni.removeStorageSync('userInfo');
        }
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        /**
         * 同步方式
         * 进来正常请求接口->获取定位->在重新获取门店列表
         */
        //获取菜单
        getMenu() {
            miniAppConfig().then((res) => {
                let menuData = JSON.parse(res.data.menu[0].value);
                menuData.forEach(item => {
                    if (item.url) {
                        // 处理相对路径 ../../images/ 或 ../images/ 或 ./images/
                        // '/packages/oldpages/static/images/'
                        if (item.url.includes('../../images/')) {
                            item.url = item.url.replace('../../images/', '/static/images/');
                        } else if (item.url.includes('../images/')) {
                            item.url = item.url.replace('../images/', '/static/images/');
                        } else if (item.url.includes('./images/')) {
                            item.url = item.url.replace('./images/', '/static/images/');
                        } else if (item.url.includes('@/images/')) {
                            // 已经是@别名格式，转换为绝对路径
                            item.url = item.url.replace('@/images/', '/static/images/');
                        } else if (item.url.includes('/images/')) {
                            // 绝对路径格式，转换为正确的静态资源路径
                            item.url = item.url.replace('/images/', '/static/images/');
                        } else {
                            item.url = '/static/images/' + item.url.replace('images/', '');
                        }
                    }
                });
                console.log(1)
                console.log(menuData);
                this.setData({
                    menuList: menuData
                });
            });
        },

        //获取门店
        getRecords() {
            getRecords(this.defalutQuery).then((res) => {
                this.setData({
                    storeList: res.data.records
                });
                uni.setStorageSync('stroreList', res.data.records[0]);
            });
        },

        //打电话
        contact(e) {
            uni.makePhoneCall({
                phoneNumber: e.currentTarget.dataset.phone
            });
        },

        // 获取定位
        getPostioning() {
            var that = this;
            uni.getLocation({
                type: 'wgs84',
                success: function (res) {
                    that.defalutQuery.latitude = res.latitude;
                    that.defalutQuery.longitude = res.longitude;
                    that.getRecords();
                }
            });
        },

        //跳转页面
        jumpPage(e) {
            let data = JSON.stringify(this.storeList[0]);
            if (e.currentTarget.dataset.item.id == 1) {
                miniAppConfig().then((res) => {
                    let str = res.data.freeDrinksTimePeriod.replace(/-/g, '/').split(',');
                    this.setData({
                        str
                    });
                    if (isDuringDate(str[0], str[1])) {
                        uni.navigateTo({
                            url: e.currentTarget.dataset.item.pageUrl + '?storeList=' + data
                        });
                        this.setData({
                            show: true
                        });
                    } else {
                        this.setData({
                            overLayshow: true,
                            show: false
                        });
                    }
                });
            } else if (e.currentTarget.dataset.item.id == 3 || e.currentTarget.dataset.item.id == 2) {
                uni.navigateTo({
                    url: '/pages/chat/index'
                });
            } else if (e.currentTarget.dataset.item.id == 4) {
                if (uni.getStorageSync('token')) {
                    uni.navigateTo({
                        url: e.currentTarget.dataset.item.pageUrl
                    });
                } else {
                    uni.navigateTo({
                        url: '/pages/login/index'
                    });
                }
            } else if ((e.currentTarget.dataset.item.id == 5)) {
                if (this.token && this.userInfo) {
                    uni.navigateToMiniProgram({
                        appId: this.menuList[0].AppID,
                        path: this.menuList[0].path,
                        envVersion: 'release'
                    });
                } else {
                    uni.navigateTo({
                        url: '/pages/login/index'
                    });
                }
            } else {
                uni.navigateTo({
                    url: e.currentTarget.dataset.item.pageUrl
                });
            }
        },

        //登录
        handelLogin() {
            uni.navigateTo({
                url: '/packages/oldpages/pages/login/index'
            });
        },

        //是否显示手机号
        handelShow() {
            this.setData({
                showmember: !this.showmember
            });
        },

        //跳转地图
        goOrder(e) {
            uni.openLocation({
                latitude: Number(e.currentTarget.dataset.item.latitude),
                // 纬度，浮点数，范围为-90~90，负数表示南纬
                longitude: Number(e.currentTarget.dataset.item.longitude),
                // 经度，浮点数，范围为-180~180，负数表示西经
                scale: 18,
                // 缩放比例，范围1~28，默认为18
                name: e.currentTarget.dataset.item.name,
                // 位置名
                address: e.currentTarget.dataset.item.address,
                // 地址的详细说明
                success: function (res) {
                    console.log(res);
                },
                fail: function (err) {
                    console.error(err);
                }
            });
        },

        //设备解锁
        Unlock(e) {
            openDoorForApp({
                deviceId: e.currentTarget.dataset.deviceid
            }).then((res) => {
                uni.showToast({
                    title: res.msg,
                    icon: 'none'
                });
            });
        },

        //会员码
        jumpMember(e) {
            uni.navigateTo({
                url: '/packages/oldpages/pages/membershipCode/index?code=' + e.currentTarget.dataset.code
            });
        },

        //扫码
        btnCode() {
            uni.scanCode({
                success: (res) => {
                    this.codehandler(res.result);
                }
            });
        },

        codehandler(code) {
            //开门的url
            if (code.includes('lixingpt.com/door') || code.includes('lixingpt.com/gate') || code.includes('lixingpt.com/shop')) {
                openDoor(code);
                return;
            }
            //通用扫码
            var params = extractUrlParameters(code);
            if (code.includes('lixingpt.com/scan')) {
                var opt = params['opt'];
                if (opt === 'deviceBoot') {
                    //启动设备的
                    bootDevice(params['devId']);
                } else if (opt === 'envelope') {
                    //领取红包的
                    takeTheEnvelope(code);
                }else if (opt === "getCoupon"){
                    //领取优惠券的
                    toGetCoupon(code);
                }
                return;
            }
            //兼容老的二维码,只有设备id的
            bootDevice(code);
        },

        //设备订单
        jump(e) {
            console.log(e);
            if (this.userInfo.capsuleUseRecords.length == 1) {
                if (e.currentTarget.dataset.devicetype == 0) {
                    uni.navigateTo({
                        url: '/pages/goodsDetail/index?id=' + e.currentTarget.dataset.id
                    });
                } else {
                    uni.navigateTo({
                        url: '/pages/laundryDetail/index?id=' + e.currentTarget.dataset.id
                    });
                }
            } else {
                uni.navigateTo({
                    url: '/pages/goods/index'
                });
            }
        }
    }
};
function takeTheEnvelope(code) {
    // 注意：这里需要从页面实例获取token和userInfo，或者通过参数传递
    // 由于这是独立函数，暂时保持原有逻辑，但建议重构为页面方法
    if (uni.getStorageSync('userInfo')) {
        uni.showLoading({
            title: '正在领取红包...'
        });
        takeEnvelopeApi(extractUrlParameters(code)).then(
            (res) => {
                uni.hideLoading();
                // wx.showToast({
                //   title: res["data"],
                //   icon: 'success',
                //   duration: 2600
                // })
                // 在领取成功后调用
                uni.showModal({
                    title: '领取成功！',
                    // 弹窗标题
                    content: res['data'] + '，请到"会员中心"查看。',
                    // 弹窗内容
                    showCancel: false,
                    // 是否显示取消按钮
                    confirmText: '好的' // 确认按钮文字
                });
            },
            (error) => {
                uni.hideLoading();
                showError(error);
            }
        );
    } else {
        saveQRAndGoToLoginPage(code);
    }
}
function bootDevice(deviceId) {
    // 注意：这里需要从页面实例获取token和userInfo，或者通过参数传递
    // 由于这是独立函数，暂时保持原有逻辑，但建议重构为页面方法
    if (uni.getStorageSync('userInfo')) {
        // 按摩舱/洗衣机
        getScan({
            code: deviceId
        }).then((res) => {
            debugger;
            let data = encodeURIComponent(JSON.stringify(res.data));
            if (res.data.device.deviceType == 0 || res.data.device.deviceType == 5) {
                uni.navigateTo({
                    url: '/pages/massage/index?data=' + data
                });
            } else {
                uni.navigateTo({
                    url: '/pages/laundry/index?data=' + data
                });
            }
        });
    } else {
        anonymousScan({
            code: deviceId
        }).then((res) => {
            let data = encodeURIComponent(JSON.stringify(res.data));
            if (res.data.device.deviceType == 0) {
                uni.navigateTo({
                    url: '/pages/massage/index?data=' + data + '&code=' + deviceId
                });
            } else {
                uni.navigateTo({
                    url: '/pages/laundry/index?data=' + data + '&code=' + deviceId
                });
            }
        });
    }
}
function openDoor(code) {
    const params = extractUrlParameters(code);
    // 注意：这里需要从页面实例获取token和userInfo，或者通过参数传递
    // 由于这是独立函数，暂时保持原有逻辑，但建议重构为页面方法
    if (uni.getStorageSync('userInfo')) {
        if (code.includes('lixingpt.com/door')) {
            openDoorDialog(params['doorId']);
        } else if (code.includes('lixingpt.com/gate')) {
            openGateDialog(params['doorId'], params['dirction']);
        } else if (code.includes('lixingpt.com/shop')) {
            openShopDoor(params['shopId'], params['opt']);
        }
    } else {
        // 未登录,缓存,去登录
        saveQRAndGoToLoginPage(code);
    }
}
function saveQRAndGoToLoginPage(code) {
    uni.setStorageSync('scanCodeCotent', code);
    //未登录跳转至登录
    const pages = getCurrentPages();
    // 获取当前页面路径,防止重复进入
    const currentPagePath = pages[pages.length - 1].route;
    if (currentPagePath !== '/pages/login/index') {
        uni.navigateTo({
            url: '/pages/login/index'
        });
    }
}
function openShopDoor(shopId, opt) {
    uni.showLoading({
        title: '欢迎光临,开门中..'
    });
    openDoorByShopId(shopId, opt).then(
        (res) => {
            uni.hideLoading();
            showSuccess();
        },
        (error) => {
            uni.hideLoading();
            showError(error);
        }
    );
}
function showError(error) {
    uni.showToast({
        title: error.msg,
        icon: 'error',
        duration: 2000
    });
}
function showSuccess() {
    uni.showToast({
        title: '门已开',
        icon: 'success',
        duration: 1600
    });
}
function openDoorDialog(number) {
    uni.showLoading({
        title: '欢迎光临,开门中..'
    });
    openNormalDoor(number).then(
        (res) => {
            uni.hideLoading();
            showSuccess();
        },
        (error) => {
            uni.hideLoading();
            showError(error);
        }
    );
}
function openGateDialog(number, direction) {
    uni.showLoading({
        title: '欢迎光临,开门中..'
    });
    openGate(number, direction).then(
        (res) => {
            uni.hideLoading();
            showSuccess();
        },
        (error) => {
            uni.hideLoading();
            showError(error);
        }
    );
}
//领取优惠券
function toGetCoupon(code) {
    console.log(code);
    console.log(3);
    var params = extractUrlParameters(code);
    const codeValue = params["code"];
    const promId = params["promId"];
    console.log(codeValue,promId);
    if (!codeValue || !promId) {
      wx.showToast({
        title: '二维码参数不完整',
        icon: 'error',
        duration: 2000
      });
      return;
    }
    
    wx.showLoading({
      title: '正在领取优惠券...',
    });
    
    // 调用真实接口
    getCoupon({
      code: codeValue,
      promId: promId
    }).then(res => {
      wx.hideLoading();
      if (res.success) {
        // 显示优惠券弹窗，使用接口返回的图片
        this.setData({
          showCoupon: true,
          couponImage: res.data.img
        });
      } else {
        wx.showToast({
          title: res.msg || '领取失败',
          icon: 'error',
          duration: 2000
        });
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err.msg || '领取失败',
        icon: 'error',
        duration: 2000
      });
    });
  }
</script>
<style>
@import './index.css';
</style>
